<template>
    <view class="content" style="position: relative;" v-if='showAll'>
        <!-- 顶部导航 -->
        <view >
            <HomeNavbar></HomeNavbar>
        </view>
		
		<view class="redbg" :style="{top:statusHeight+'px'}">
		</view>
		
		<!-- <view style="position: relative;top: -479upx;"> -->
		<view style="margin-bottom:80upx;">
			<!-- 首页板块 -->
			<template v-for="item in homeData">
			    <MmvHomeTemplate :key="item.components" :isComponents="item.components" :homeData="homeData"></MmvHomeTemplate>
			</template>
		</view>
        
        <!-- 底部导航 -->
        <HomeTabbar :tab="0"></HomeTabbar>
        <!-- 登录弹窗 -->
        <LoginMask></LoginMask>
		
		<!-- <HomeCouponDialog></HomeCouponDialog> -->
		
		<HomeSelectStore></HomeSelectStore>
		
		
		
		<!-- #ifdef MP-WEIXIN -->
		<a-tip isCustom></a-tip>
		<!-- #endif -->
		<u-popup :show="mobileVerification" mode="bottom" round="10">
			<view class='info-box'>
				<view class='title-box'>
					<view class='title-box-text'>短信验证</view>
					<view class="close-img-box" @click='mobileVerification=false'>
						<image class="close-img" src="../../static/window_icon_close.png"></image>
					</view>
					
				</view>
				<view class='title-box'>
					<view class='info-value-text'>
						 <u--input placeholder="请输入验证码" border="surround" v-model="phoneCode"></u--input>
					</view>
					<u-toast ref="uToast"></u-toast>
					<u-code :seconds="seconds"  ref="uCode" 
						@change="codeChange"></u-code>
					<u-button @tap="getCode">{{tips}}</u-button>
				</view>
				<view class="bottom2" @click='confirm()'>确定</view>
			</view>
		</u-popup>
		<u-popup :show="phoneStatus" mode="bottom" round="10">
			<view class='info-box'>
				<view class='title-box'>
					<view class='title-box-text'>获取手机号</view>
					<view class="close-img-box" @click='phoneStatus=false'>
						<image class="close-img" src="../../static/window_icon_close.png"></image>
					</view>
					
				</view>
				<view class='title-box'>
					<button style="font-size: 16px;" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">授权并获取手机号</button>
				</view>
			</view>
		</u-popup>
		<u-popup :show="infoStatus" mode="bottom" round="10">
			<view class='info-box'>
				<view class='title-box'>
					<view class='title-box-text'>用户授权</view>
					<view class="close-img-box" @click='infoStatus=false'>
						<image class="close-img" src="../../static/window_icon_close.png"></image>
					</view>
					
				</view>
				<view class='title-box'>
					<button class="button-login" @click="getuserinfo" >
					    <text>授权用户信息</text>
					</button>
				</view>
			</view>
		</u-popup>
		
    </view>
</template>

<script>
import HomeNavbar from '@/components/layout/navbar.vue';
import MmvHomeTemplate from './components/mmv-home-template.vue';
import HomeTabbar from '@/components/layout/tabbar.vue';
import LoginMask from '@/components/layout/login-mask.vue';
// import HomeCouponDialog from './components/home-coupon-dialog.vue';
import HomeSelectStore from './components/home-select-store.vue';
import * as loginApi from '@/common/apis/login-api.js';
import WXBizDataCrypt from "@/util/WXBizDataCrypt.js"


import {strToObj} from '@/util/index.js';

import ATip from '@/components/aTip.vue';

export default {
    components: {
        HomeNavbar,
        MmvHomeTemplate,
        HomeTabbar,
        LoginMask,
		ATip,
		// HomeCouponDialog,
		HomeSelectStore
    },
    data() {
        return {
			statusHeight:0,
			mobileVerification:false,
			tips: '',
			seconds: 60,
			phoneCode:'',
			phoneStatus:false,
			idmuToken:'',
			infoStatus:false,
			showAll:true,
        };
    },
    computed: {
        isShowLogin() {
            return this.$store.state.app.isShowLogin;
        },
        homeData() {
            return this.$store.state.home.homeData;
        },
        openid() {
            return this.$store.state.user.openid;
        },
        deptId() {
            return this.$store.state.user.deptId;
        },
        userInfo() {
            return this.$store.state.user.userInfo;
        },
    },
    onShow() {
    	uni.$on('emit', res=>{
    		this.showAll = false
			setTimeout(()=>{
				this.showAll = true
			},100)
			
    	})
		console.log('进来了')
		
    },
	async onLoad(op) {
		let result = await loginApi.store();
		this.statusHeight = uni.getSystemInfoSync().statusBarHeight + 44;
		wx.showShareMenu({
			withShareTicket:true,
		  menus: ['shareAppMessage','shareTimeline']
		})
        this.$store.dispatch('home/getHomeData', '首页');
		// const info = this.$store.dispatch('user/wxLogin');//获取openid
		const scene = decodeURIComponent(op.scene);
		if(!uni.$u.test.isEmpty(op.scene)){
			if(op.scene.indexOf('%')>-1){
				//scene是个对象，应该是门店二维码
				let op_qrcode = strToObj(scene);
				// 从二维码获取门店id
				if (op_qrcode.deptId) {
					this.$store.commit('user/saveSourceType', 2);
				    this.$store.commit('user/savedeptId', op_qrcode.deptId);
					uni.setStorageSync('deptId', op_qrcode.deptId);
				}
				
				// 从二维码获取userid
				if (op_qrcode.userId) {
					this.$store.commit('user/saveSourceType', 2);
					this.$store.commit('user/saveuserId', op_qrcode.userId);
				}
				
				// 从二维码获取channelId
				if (op_qrcode.channelId) {
					this.$store.commit('user/saveSourceType', 2);
					this.$store.commit('user/savechannelId', op_qrcode.channelId);
				}
				
			}else{
				//scene值只是个数字，应该是邀请分享来的
				// 存入分享上级
				this.$store.commit('user/saveCustomerId', scene);
			}
		}
		
		
		
		
		//分享有两种 1，直接进入首页    2，打开对应页面再点左上角回到首页
		
		//情况1 直接进入首页 保存分享人id和门店id
		if(!uni.$u.test.isEmpty(op.customerId)){
			this.$store.commit('user/saveCustomerId', op.customerId);
		}
		if(!uni.$u.test.isEmpty(op.deptId)){
			this.$store.commit('user/saveSourceType', 4);
			this.$store.commit('user/savedeptId', op.deptId);
			uni.setStorageSync('deptId', op.deptId);
		}
		
		
		
		
		//情况2  从活动等页面回到首页
		if(!uni.$u.test.isEmpty(getApp().globalData.tempDeptId)){
			
			this.$store.commit('user/saveSourceType', 4);
			this.$store.commit('user/savedeptId', getApp().globalData.tempDeptId);
			uni.setStorageSync('deptId', getApp().globalData.tempDeptId);
			getApp().globalData.tempDeptId = '';
		}
		
		if(!uni.$u.test.isEmpty(getApp().globalData.tempCustomerId)){
			
			this.$store.commit('user/saveCustomerId', getApp().globalData.tempCustomerId);
			getApp().globalData.tempCustomerId = '';
		}
		
		this.$store.commit('user/saveDeptChoseFlag', getApp().globalData.deptchose);

		
		//如果有deptId,不需要再选门店
		// if(!uni.$u.test.isEmpty(this.$store.state.user.deptId)){
		// 	// 获取门店信息
		// 	await this.$store.dispatch('app/getStoreInfo', this.$store.state.user.deptId);
		// }
		// uni.$on('candeptchose', res=>{
			
		// 	console.log('收到可切换门店通知');
			
		// 	//如果deptId是空，弹框选择门店
		// 	if(uni.$u.test.isEmpty(this.$store.state.user.deptId)){
		// 		// 获取门店信息 
				
		// 		console.log('无默认门店，获取门店');
				
		// 		this.$store.dispatch('app/getStoreInfo', this.$store.state.user.deptId)
		// 	}
		// })
		
		
    },
	mounted() {
		console.log('进来了12323')
		// this.infoStatus = true
		// this.getToken()
	},
	methods:{
		/** 绑定用户信息 */
		getuserinfo() {
		    uni.getUserProfile({
		        desc: '绑定用户信息',
		        success: (detail) => {
					this.infoStatus = false
		           this.getToken()
		        },
		        fail: (error) => {
		        },
		    })
		},
		// 获取登录认证
		getToken(){
			var that = this
			uni.login({
				 provider: 'weixin',
				 success: function ({ code }) {
					uni.setStorageSync('code', code);
					// 与第三方接口调通时开启
					loginApi.getIdmtoken({code:code}).then((res)=>{
						 if(res.code==811){
							 that.mobileVerification = true
						 }else{
							 that.$store.commit('user/saveAccessToken', res.access_token);
							 uni.setStorageSync('accessToken', res.access_token);
							 uni.setStorageSync('userInfo', res);
							 uni.setStorageSync('phone',res.phone)
							 let userInfo = uni.getStorageSync('userInfo')
							 setTimeout(()=>{
								 path: '/pages/home/home?customerId=' + userInfo.customerId + '&deptId='+uni.getStorageSync('deptId')
							 })	 
						 }
					})
				 },
				 fail: function (err) {
					 uni.showToast({ title: '请前往小程序使用完整服务', icon: 'none' });
					 reject(err);
				 },
			 })
			
		},
		
		// 获取手机验证码
		getNumber(){
			loginApi.getPhoneNum({phone:uni.getStorageSync('phoneNumber')}).then((res)=>{
				this.idmuToken = res
				this.phoneStatus = false
				this.mobileVerification=true
			})
		},
		// 获取手机号
		onGetPhoneNumber(e){
			if(uni.getStorageSync('phoneNumber')){
				this.getNumber()
			}else{
				var that = this
				uni.login({
					 provider: 'weixin',
					 success: function ({ code }) {
						uni.setStorageSync('code', code);
						uni.request({
							url: 'https://api.weixin.qq.com/sns/jscode2session', // 请求微信服务器
							method: 'GET',
							data: {
								appid: 'wx7b602d53181a3f22', //你的小程序的APPID
								secret: '1397153840e208dcf7a7e70c24f253ab', //你的小程序秘钥secret,  
								js_code: code, //uni.login 登录成功后的code
								grant_type: 'authorization_code' //此处为固定值
							},
							success: (res) => {
								let pc = new WXBizDataCrypt('wx7b602d53181a3f22', res.data.session_key);
								let data = pc.decryptData(e.detail.encryptedData, e.detail.iv);
								if (data.phoneNumber != '') {
									uni.setStorageSync('phoneNumber', data.phoneNumber);
									that.phoneStatus = false
									that.mobileVerification=true
								}
							}
						});
					 },
					 fail: function (err) {
						 uni.showToast({ title: '请前往小程序使用完整服务', icon: 'none' });
						 reject(err);
					 },
				 })
			}	
		},
		// 验证码确认
		confirm(){
			var that = this
			var phoneCode1 = that.phoneCode
			var idmuToken1 = that.idmuToken
			uni.login({
				 provider: 'weixin',
				 success: function ({ code }) {
					uni.setStorageSync('code', code);
					if(uni.getStorageSync('phoneNumber') && phoneCode1 && code && idmuToken1){
						let param ={
							phone:uni.getStorageSync('phoneNumber'),
							verifyCode:phoneCode1,
							code:code,
							idmuToken:idmuToken1
						}
						loginApi.postBindInfo(param).then((res)=>{
							that.mobileVerification=false
							that.getToken()
						})	
					}
				 },
				 fail: function (err) {
					 uni.showToast({ title: '请前往小程序使用完整服务', icon: 'none' });
					 reject(err);
				 },
			 })
			
		},
		codeChange(text) {
			this.tips = text;
		},
		getCode() {
			if(uni.getStorageSync('phoneNumber')){
				this.getNumber()
				if(this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					uni.showLoading({
						title: '正在获取验证码'
					})
					setTimeout(() => {
						uni.hideLoading();
						// 这里此提示会被this.start()方法中的提示覆盖
						uni.$u.toast('验证码已发送');
						// 通知验证码组件内部开始倒计时
						this.$refs.uCode.start();
					}, 2000);
				} else {
					uni.$u.toast('倒计时结束后再发送');
				}
			}else{
				this.mobileVerification = false
				this.phoneStatus = true
			}	
		},
	}
};
</script>

<style lang="scss" scoped>
	.phone-box{
		width:400px;
		height: 400px;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.info-box{
			background-color:#F8F8F8 ;
			padding:16px;
			.bottom2 {
				width: 100%;
				height: 40px;
				margin: 0 auto;
				text-align: center;
				line-height: 40px;
				background-color: $redec;
				border-radius: 4px;
				margin-top:20px;
				color:#ffffff;
				font-size: 16px;
			}
			.value-box-title{
				display: flex;
				align-items: center;
				font-size: 14px;
				color:#000000;
				margin-bottom: 12px;
				.close-img{
					width: 16px;
					height: 16px;
				}
			}
			.value-box-value{
				background-color: #ffffff;
				padding:12px;
				color:#999999 ;
				font-size: 12px;
				.value-name{
					color:#000000 ;
					font-size:16px;
					margin-bottom:12px ;
					font-weight: bold;
				}
			}
			.title-box{
				width: 100%;
				display: flex;
				justify-content: space-between;
				margin-bottom: 16px;
				.title-box-text{
					font-size:16px ;
					font-weight: bold;
					color:#000000,
					
				}
				.close-img-box{
					width:17px ;
					height:17px;
					
					.close-img{
						width:16px ;
						height:16px;
					}
				}
				.info-value-text{
					width:500px
				}
				
			}
		}
	.redbg{
		z-index: -99;
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		// position: sticky;
		// top: calc(44px + var(--status-bar-height));
		// top: 128rpx;
		// width: 100%;
		height: 500upx;
		background: linear-gradient(to right bottom, #EEF7FE, #D8ECFC, #F8F8F8 );
	}
	
</style>
